package com.md.common.utils.qiniu;

import com.google.gson.Gson;
import com.md.common.utils.HttpUtils;
import com.md.common.utils.UUIDUitl;
import com.md.common.utils.date.DateUtil;
import com.md.common.utils.file.FileUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;

/**
 * 功能描述：七牛云存储工具
 *
 * @author lujianping@oak168.com
 * @version 1.0
 * @date 2018-7-3 10:35
 * @since JDK 1.8
 */
public class QiniuUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(QiniuUtil.class);

    private static String ACCESS_KEY = "xF1lxCkwv0z5XGKbprIQDCkJmSgTBqnjyaVdJ-9S";
    private static String SECRET_KEY = "W1U1xfhL8jYAkhyR2JaYCeEfoARV2KbmmuQX2IuB";
    public static String FILE_ACCESS_HOST = "http://pb9t9wnew.bkt.clouddn.com/";

    public static void init(QiniuConfig qiniuConfig) {
        ACCESS_KEY = qiniuConfig.getAccessKey();
        SECRET_KEY = qiniuConfig.getSecretKey();
        FILE_ACCESS_HOST = qiniuConfig.getFileAccessHost();
    }

    public static String uploadPic(byte[] bytes) throws Exception {
        return upload(QiniuBucketEnum.DCESHOP.getName(), QiniuParentFilePathEnum.PIC.getName(), generatePicName(), bytes);
    }

    private static String generatePicName() {
        return System.currentTimeMillis() + UUIDUitl.generateString(12);
    }

    public static String upload(String bucket, String parentPath, String fileName, byte[] bytes) {
        LOGGER.info("文件上传start，bucket：{}", bucket);

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.autoZone());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以时间戳作为文件名
        if (StringUtils.isBlank(fileName)) {
            fileName = System.currentTimeMillis() + "";
        }
        String key = parentPath + "/" + fileName;
        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
        //...生成上传凭证，然后准备上传
        String upToken = createToken(bucket);
        try {
            Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            LOGGER.info("文件上传成功，key：{}，hash：{}", putRet.key, putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                LOGGER.error("文件上传异常，response：{}", r.toString(), ex);
                LOGGER.error("文件上传异常，bodyString：{}", r.bodyString(), ex);
            } catch (QiniuException ex2) {
                //ignore
                return null;
            }
        }
        return null;
    }

    public static String upload(String bucket, String parentPath, String fileName, File file) throws Exception {
        LOGGER.info("文件上传start，bucket：{}", bucket);

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.autoZone());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以时间戳作为文件名
        if (StringUtils.isBlank(fileName)) {
            fileName = System.currentTimeMillis() + "";
        }
        String key = parentPath + "/" + fileName;
        try {
            InputStream fis = new FileInputStream(file);
            byte[] fisArray = new byte[fis.available()];
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(fisArray);
            //...生成上传凭证，然后准备上传
            String upToken = createToken(bucket);

            Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            LOGGER.info("文件上传成功，key：{}，hash：{}", putRet.key, putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                LOGGER.error("文件上传异常，response：{}", r.toString(), ex);
                LOGGER.error("文件上传异常，bodyString：{}", r.bodyString(), ex);
            } catch (QiniuException ex2) {
                //ignore
                throw ex2;
            }
        } catch (IOException e) {
            LOGGER.error("文件上传异常，读取文件失败", e);
            throw e;
        }
        return null;
    }

    private static String createToken(String bucket) {
        LOGGER.info("创建上传凭证start，bucket：{}", bucket);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(bucket);
        LOGGER.info("创建上传凭证成功，upToken：{}", upToken);
        return upToken;
    }

    public static byte[] downLoad(String fileName) throws Exception {
        LOGGER.info("下载图片start，fileName：{}", fileName);
        HttpResponse res = HttpUtils.doGet(FILE_ACCESS_HOST, fileName, new HashMap<>(), new HashMap<>());
        if (res != null) {
            byte[] file = EntityUtils.toByteArray(res.getEntity());
            LOGGER.info("下载图片end，fileName：{}", fileName);
            return file;
        }
        LOGGER.info("下载图片失败，fileName：{}", fileName);
        return null;
    }

    public static byte[] downLoad(String host, String fileName) throws Exception {
        LOGGER.info("下载图片start，fileName：{}", fileName);
        HttpResponse res = HttpUtils.doGet(host, fileName, new HashMap<>(), new HashMap<>());
        if (res != null) {
            byte[] file = EntityUtils.toByteArray(res.getEntity());
            LOGGER.info("下载图片end，fileName：{}", fileName);
            return file;
        }
        LOGGER.info("下载图片失败，fileName：{}", fileName);
        return null;
    }

    public static void main(String[] arg) throws Exception {
                File file = new File("E:\\1530697159(1).jpg");
                upload(QiniuBucketEnum.DCESHOP.getName(), QiniuParentFilePathEnum.PIC.getName(), null, FileUtil.getBytes(file));

//        byte[] file = downLoad("kpInsurePic/1512796462554G1MgrLbzaXYr");
        LocalDate firstday = LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDay = LocalDate.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());

        System.out.println("本月的第一天" + firstday);
        System.out.println("本月的最后一天" + lastDay);

        LocalDate now = LocalDate.now();
        LocalDate startDate = DateUtil.getPreviousMonthFirstDay(now);
        LocalDate endDate = DateUtil.getPreviousMonthLastDay(now);

        System.out.println("本月的第一天" + DateUtil.formaterDate(startDate));
    }


}
